<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input :disabled="isHistory" v-model="model.name" placeholder="请输入名称" ></a-input>
            </a-form-model-item>
          </a-col>
          
          <a-col :span="8">
            <a-form-model-item label="运维类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="devopsPersontype">
              <j-dict-select-tag :disabled="isHistory" type="list" v-model="model.devopsPersontype" dictCode="devops_persontype" placeholder="请选择运维类型" />
            </a-form-model-item>
          </a-col>
          <template v-if="toggleSearchStatus">
          <a-col :span="8">
            <a-form-model-item label="触发类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="triggerType">
              <j-dict-select-tag type="list" v-model="model.triggerType" dictCode="trigger_type" placeholder="请选择触发类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="初次触发时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="triggerTime">
              <j-date placeholder="请选择初次触发时间" v-model="model.triggerTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="重复次数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repeatNumber">
              <a-input v-model="model.repeatNumber" placeholder="请输入重复次数" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="重复间隔" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repeatGap">
              <a-input v-model="model.repeatGap" placeholder="请输入重复间隔" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="重复间隔单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repeatGapUnit">
              <j-dict-select-tag type="list" v-model="model.repeatGapUnit" dictCode="yks_unit,name,id" placeholder="请选择重复间隔单位" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="上次保养时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maintenanceLastTime">
              <j-date placeholder="请选择上次保养时间" v-model="model.maintenanceLastTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="下次保养时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maintenanceNextTime">
              <j-date placeholder="请选择下次保养时间" v-model="model.maintenanceNextTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="保养时间段开始" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maintenanceQuantumstart">
              <j-date placeholder="请选择保养时间段开始" v-model="model.maintenanceQuantumstart" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="保养时间段结束" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maintenanceQuantumend">
              <j-date placeholder="请选择保养时间段结束" v-model="model.maintenanceQuantumend" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" >
            <a-form-model-item label="保养内容" :labelCol="labelCol1" prop="maintenanceContext">
              <a-textarea v-model="model.maintenanceContext" placeholder="请输入保养内容" :auto-size="{ minRows: 3, maxRows: 20 }"></a-textarea>
            </a-form-model-item>
          </a-col>
          </template>
          <a-col :span="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="运维材料表" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="yksEquipmentDevopsMaterialDetailTable.loading"
          :columns="yksEquipmentDevopsMaterialDetailTable.columns"
          :dataSource="yksEquipmentDevopsMaterialDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          :edit-config="{
            trigger: 'click',
            mode: 'cell',
            showStatus: true,
            showIcon: false,
            activeMethod: this.activeCellMethod,
          }"  
          >
          <span slot='toolbarSuffix'  >
              <a-button :disabled="formDisabled" type="primary"  @click="()=>multiSelect('material')" icon="copy">多选</a-button>
          </span>
           </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="产品运维表" :key="refKeys[1]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[1]"
          :loading="yksEquipmentDevopsProductDetailTable.loading"
          :columns="yksEquipmentDevopsProductDetailTable.columns"
          :dataSource="yksEquipmentDevopsProductDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          :edit-config="{
            trigger: 'click',
            mode: 'cell',
            showStatus: true,
            showIcon: false,
            activeMethod: this.activeCellMethod,
          }"       >
          <span slot='toolbarSuffix' >
            <a-button :disabled="formDisabled" @click="()=>multiSelect('product')" type="primary" icon="copy">多选</a-button>
          </span>
        </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="运维状态表" :key="refKeys[2]" :forceRender="true" v-show="formDisabled==true">
        <j-vxe-table
          keep-source
          :ref="refKeys[2]"
          :loading="yksEquipmentDevopsStatusTable.loading"
          :columns="yksEquipmentDevopsStatusTable.columns"
          :dataSource="yksEquipmentDevopsStatusTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="false"
          :edit-config="{
            showIcon: false,
          }"
          />
      </a-tab-pane>
    </a-tabs>
    <!-- <a-drawer width="600" placement="right" :visible="processSelectVisible" @close="processSelectVisible = false">
      <template>
        <div>
          <j-popup v-model="popupValue" code="demo" field="name" orgFields="name" destFields="name" :multi="true" @input="popupCallback"/>
        </div>
      </template>
    </a-drawer> -->
      <!-- <onl-cgreport-select-modal
        ref="selectModal"
        title="选择项目零件"
        reportId="1742443021656961025"
        :width="1100"
        :params="this.getParam()"
        :multiSelectable="true"
        @callback="callBack"
      /> -->
    <j-onl-query-modal ref="selectModal" :code="this.runDataQuery" :param="this.getParam()" field="name"
      orgFields="name" destFields="name" :multi="true" @input="callBack" />
  </a-spin>
</template>

<script>

  // import { getAction } from '@/api/manage'
  import { httpAction, getAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JOnlQueryModal from '../../../../components/jeecg/JOnlQueryModal.vue'

  export default {
    name: 'YksEquipmentDevopsServiceForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
        JOnlQueryModal,
    },
    data() {
      return {
        runDataQuery: 'equipmentMaterialQuery',
        popupValue : '',
        serviceType:'',
        currentEquipmentId:'',
        processSelectVisible: false,
        toggleSearchStatus:false,
        dataStatus:'1',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 },
        },
        labelCol1: {
          xs: { span: 24 },
          sm: { span: 2 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 17 },
        },
        model:{
          status: '1'
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 0,
        validatorRules: {
           name: [
              { required: true, message: '请输入名称!'},
           ],
           devopsPersontype: [
              { required: true, message: '请输入运维类型!'},
           ],
        },
        refKeys: ['yksEquipmentDevopsMaterialDetail', 'yksEquipmentDevopsProductDetail', 'yksEquipmentDevopsStatus', ],
        tableKeys:['yksEquipmentDevopsMaterialDetail', 'yksEquipmentDevopsProductDetail', 'yksEquipmentDevopsStatus', ],
        activeKey: 'yksEquipmentDevopsMaterialDetail',
        // 运维材料表
        yksEquipmentDevopsMaterialDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '运维类型',
              key: 'serviceType',
              type: JVXETypes.select,
              options:[],
              dictCode:"service_type",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'1',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },

            {
              title: '材料',
              key: 'materialName',
              type: JVXETypes.popup,
              popupCode:"equipmentMaterialQuery",
              field:"materialId",
              orgFields:"id,material_id,material_name,location_number,material_code,change_gap,maintenance_gap,maintenance_date,check_gap,check_date,change_date",
              destFields:"partConfigId,materialId,materialName,locationNumber,materialCode,changeGap,maintenanceGap,maintenanceDate,checkGap,checkDate,changeDate",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              param: this.getParam(),
            },
            {
              title: '位号',
              key: 'locationNumber',
               type: JVXETypes.input,
              width:"80px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '保养说明',
              key: 'remark',
               type: JVXETypes.textarea,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '现场保养说明',
              key: 'serviceRemark',
               type: JVXETypes.textarea,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '现场保养图片',
              key: 'attachments',
              type: JVXETypes.image,
              token:true,
              responseName:"message",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '检查间隔(月)',
              key: 'checkGap',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '保养间隔(月)',
              key: 'maintenanceGap',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '更换间隔(月)',
              key: 'changeGap',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '检查日期',
              key: 'checkDate',
              type: JVXETypes.date,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '保养日期',
              key: 'maintenanceDate',
              type: JVXETypes.date,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '更换日期',
              key: 'changeDate',
              type: JVXETypes.date,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },

          ]
        },
        // 产品运维表
        yksEquipmentDevopsProductDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '运维类型',
              key: 'serviceType',
              type: JVXETypes.select,
              options:[],
              dictCode:"service_type",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'1',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '化学药剂',
              key: 'productName',
              type: JVXETypes.popup,
              popupCode:"equipmentProductQuery",
              field:"productId",
              orgFields:"id,product_id,product_name,location_number,product_code,change_gap,maintenance_gap,maintenance_date,check_gap,check_date,change_date",
              destFields:"partConfigId,productId,productName,locationNumber,productCode,changeGap,maintenanceGap,maintenanceDate,checkGap,checkDate,changeDate",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              param:this.getParam()
            },
            {
              title: '位号',
              key: 'locationNumber',
               type: JVXETypes.input,
              width:"80px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '保养说明',
              key: 'remark',
               type: JVXETypes.textarea,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '现场保养说明',
              key: 'serviceRemark',
               type: JVXETypes.textarea,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '现场保养图片',
              key: 'attachments',
              type: JVXETypes.image,
              token:true,
              responseName:"message",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '检查间隔(月)',
              key: 'checkGap',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '保养间隔(月)',
              key: 'maintenanceGap',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '更换间隔(月)',
              key: 'changeGap',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '检查日期',
              key: 'checkDate',
              type: JVXETypes.date,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '保养日期',
              key: 'maintenanceDate',
              type: JVXETypes.date,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '更换日期',
              key: 'changeDate',
              type: JVXETypes.date,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },            
          ]
        },
        // 运维状态表
        yksEquipmentDevopsStatusTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '运维状态',
              key: 'status',
              type: JVXETypes.select,
              options:[],
              dictCode:"devops_status",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '说明',
              key: 'remark',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '创建人',
              key: 'createBy',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '创建日期',
              key: 'createTime',
              type: JVXETypes.date,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          addHis: "/srv/yksEqmDevopsServiceHis/add",
          add: "/srv/yksEquipmentDevopsService/add",
          edit: "/srv/yksEquipmentDevopsService/edit",
          queryById: "/srv/yksEquipmentDevopsService/queryById",
          yksEquipmentDevopsMaterialDetail: {
            list: '/srv/yksEquipmentDevopsService/queryYksEquipmentDevopsMaterialDetailByMainId'
          },
          yksEquipmentDevopsProductDetail: {
            list: '/srv/yksEquipmentDevopsService/queryYksEquipmentDevopsProductDetailByMainId'
          },
          yksEquipmentDevopsStatus: {
            list: '/srv/yksEquipmentDevopsService/queryYksEquipmentDevopsStatusByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      EquipmentId : {
        type : String,
        default : '',
        required: true
      },
      isHistory:{
         type : Boolean,
         required: true,
         default:false,
       },
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      handleToggleSearch(){
        this.toggleSearchStatus = !this.toggleSearchStatus;
      },
      popupCallback(value,rows){
          console.log(rows)
      },
      multiSelect(query) {
         if (query == 'material') {
          this.runDataQuery = 'equipmentMaterialQuery'
         } else {
          this.runDataQuery = 'equipmentProductQuery'
         }
         this.$refs.selectModal.openModal()
      },
      callBack(value,rows) {
        console.log(rows)
        this.updateItemDataSource(rows)
      },
      activeCellMethod({ row, rowIndex, column, columnIndex }) {
        let name = column.own.key
        if(!this.isHistory) {
          if (['serviceRemark','attachments','changeGap','maintenanceGap','checkGap','checkDate','changeDate','maintenanceDate'].includes(name)){
            return false
          }
        } else {
          if (['remark','changeGap','maintenanceGap','checkGap','checkDate','changeDate','maintenanceDate'].includes(name)){
            return false
          }
        }
        return true},
      getParam(e){
        console.log(this.EquipmentId)
        return {equipment_id:this.EquipmentId}
      },
      // getParam1(e){
      //   console.log(this.EquipmentId)
      //   return {equipment_id:this.EquipmentId}
      // },
      updateItemDataSource(data) {
        let activeKey = ''
         if ( this.runDataQuery == 'equipmentMaterialQuery') {
           activeKey = 'yksEquipmentDevopsMaterialDetail'
         } else {
           activeKey = 'yksEquipmentDevopsProductDetail'
         }
        let that = this
        console.log(data)
        setTimeout(() => {
          if (data) {
            let fullData = this.$refs[activeKey].$refs.vxe.getTableData().fullData
            console.log(fullData)
            if (this.runDataQuery == 'equipmentMaterialQuery') {
                data.forEach((v, k) => {
                  v.materialId = v.material_id
                  v.materialName = v.material_name
                  v.materialCode = v.material_code
                  v.changeGap = v.change_gap
                  v.maintenanceGap = v.maintenance_gap
                  v.checkGap = v.check_gap
                  v.checkDate = v.check_date
                  v.changeDate = v.change_date
                  v.maintenanceDate = v.maintenance_date
                  v.partConfigId = v.id
                  v.rowId = v.id
                  delete v.id
                }, this)
                data = data.filter((item) => {
                  let flag = true
                  fullData.forEach((v, k) => {
                    if (item.materialName == v.materialName) {
                      flag = false
                    }
                  })
                  return flag
                })
            } else {
                data.forEach((v, k) => {
                  v.productId = v.product_id
                  v.productName = v.product_name
                  v.productCode = v.product_code
                  v.changeGap = v.change_gap
                  v.maintenanceGap = v.maintenance_gap
                  v.checkGap = v.check_gap
                  v.checkDate = v.check_date
                  v.changeDate = v.change_date
                  v.maintenanceDate = v.maintenance_date
                  v.partConfigId = v.id
                  v.rowId = v.id
                  delete v.id
                }, this)
                data = data.filter((item) => {
                  let flag = true
                  fullData.forEach((v, k) => {
                    if (item.productName == v.productName) {
                      flag = false
                    }
                  })
                  return flag
                })
            }
            this.$refs[activeKey].addRows(data)
          }
        }, 600)
      },
            /** 发起请求，自动判断是执行新增还是修改操作 */
      request(formData) {
        debugger
        let url = this.url.add, method = 'post'
        if (this.model.id) {
          url = this.url.edit
          method = 'put'
        }
        if (this.isHistory) {
          url = this.url.addHis
          method = 'post'
        }
        this.confirmLoading = true
        console.log("formData===>",formData);
        httpAction(url, formData, method).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },
      addBefore(){
        this.yksEquipmentDevopsMaterialDetailTable.dataSource=[]
        this.yksEquipmentDevopsProductDetailTable.dataSource=[]
        this.yksEquipmentDevopsStatusTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.model.equipmentId = this.currentEquipmentId
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.yksEquipmentDevopsMaterialDetail.list, params, this.yksEquipmentDevopsMaterialDetailTable)
          this.requestSubTableData(this.url.yksEquipmentDevopsProductDetail.list, params, this.yksEquipmentDevopsProductDetailTable)
          this.requestSubTableData(this.url.yksEquipmentDevopsStatus.list, params, this.yksEquipmentDevopsStatusTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        this.model.status = this.dataStatus
        this.model.devopsServiceId = this.model.id        
        let main = Object.assign(this.model, allValues.formValue)
        if (this.isHistory) {
          this.model.id = null;
          this.model.createBy = null;
          this.model.createTime = null;
          allValues.tablesValue[0].tableData.forEach(element => {
            delete element.createBy
            delete element.createTime
            delete element.id
          });
          allValues.tablesValue[1].tableData.forEach(element => {
            delete element.id
            delete element.createBy
            delete element.createTime
          });
            return {
              ...main, // 展开
              yksEqmDevopsMaterialDetailHisList: allValues.tablesValue[0].tableData,
              yksEqmDevopsProductDetailHisList: allValues.tablesValue[1].tableData,
            }
        } else {
            return {
              ...main, // 展开
              yksEquipmentDevopsMaterialDetailList: allValues.tablesValue[0].tableData,
              yksEquipmentDevopsProductDetailList: allValues.tablesValue[1].tableData,
              yksEquipmentDevopsStatusList: allValues.tablesValue[2].tableData,
            }
        }

      },
      validateError(msg){
        this.$message.error(msg)
      },

    }
  }
</script>

<style scoped>
</style>